/*!
 * Test plugin for Editor.md
 *
 * @file        test-plugin.js
 * @author      pandao
 * @version     1.2.0
 * @updateTime  2015-03-07
 * {@link       https://github.com/pandao/editor.md}
 * @license     MIT
 */

(function() {

    var factory = function(exports) {
        var $ = jQuery; // if using module loader(Require.js/Sea.js).
        var pluginName = "7dtime";

        // exports.fn.testMind = function(p1, p2) {
        //     console.log("testMind");
        // }

        $.fn.draw7dtime = function() {
            try {
                var parsed = JSON.parse($(this).text());
            } catch (err) {
                console.log("Woops! Error parsing", err);
                return;
            }

            var html = new drawFragment(new fragment(parsed));


            this.empty().append(html);
            return html;

        };


        //组合成碎片图数组并返回
        var fragment = function(data) {
            var fragmentData = [];
            for (var i = 0; i < 24 * 6; i++) {
                var title = parseInt(i / 6) + ':' + (i % 6 * 10);
                fragmentData.push({ time: 0, item: [], title: title, tags: {}, count: 0 });
            }

            //获取清单标签
            this.getTag = function(tags) {
                var tag = '';
                var tagArr = ['critical', 'high', 'low', 'minor', 'life'];
                for (var i = 0; i < tagArr.length; i++) {
                    if (tags[tagArr[i]] !== undefined)
                        return tagArr[i];
                }

            }
            //一个任务会有多次暂停情况，将一个任务分解为全部相连的小任务
            this.cutItems = function(tags) {
                var started = tags['started'],
                    done = tags['done']?tags['done']:tags['cancelled'];
                var toggle = tags['toggle'];
                let toggleArr = [];
                if (toggle) {
                    //替换、切割
                    toggle = toggle.replace(/\ (\d{2}-\d{2}-\d{2})/g, ' 20$1').trim();
                    toggleArr = toggle.replace(/\ (\d{4}-\d{2}-\d{2})/g, '|$1').split('|');
                    //排序

                    for (let i = 0; i < toggleArr.length; i++) {
                        toggleArr[i] = moment(toggleArr[i]).format('X');
                    }
                    toggleArr.sort();
                    if (toggleArr.length % 2 != 0 && toggleArr.length > 1) {
                        toggleArr.splice(toggleArr.length - 1, 1);
                    }
                    for (let i = 0; i < toggleArr.length; i++) {
                        toggleArr[i] = moment.unix(toggleArr[i]).format('YYYY-MM-DD HH:mm');
                    }
                }
                var timeGroup = [started, ...toggleArr];
                if(done) timeGroup.push(done);
                for (let i = 0; i < timeGroup.length; i += 2) {
                    tags['started'] = timeGroup[i];
                    tags['done'] = timeGroup[i + 1];
                    this.fillItems(tags);
                }


            }

            //开始或结束时间点
            this.getTimePoint = function(time){
                
                if(moment(time).isBefore(moment(today||time).format("YYYY-MM-DD"))){
                    return 0;
                }
                if(moment(time).isAfter(moment(today||time).format("YYYY-MM-DD 23:59:59"))){
                    return 9;
                }
                return moment(time).minute()%10;
            }

            //填充多个小碎片
            this.fillItems = function(tags){
                if(!(tags['started']&&tags['done'])) return ;
                var started = tags['started'], done = tags['done'];
                var startItemKey = this.getIndex(started);
                var endItemKey = this.getIndex(done);
                var start=this.getTimePoint(started), end;
                
                for(var ItemKey=startItemKey; ItemKey<=endItemKey; ItemKey++){
                    end = 9;
                
                    if(ItemKey==endItemKey) end=this.getTimePoint(done);
                    fragmentData[ItemKey] = this.fillItem(fragmentData[ItemKey], start, end, this.getTag(tags));
    
                    start = 0;
                }
            }

            //空心圆
            this.circleItem = function(tags){
                var index = this.getIndex(tags['started']||tags['done']||tags['cancelled']);
                fragmentData[index]['circle'] = true;
            }

            //填充每个小碎片
            this.fillItem = function(item, start, end, tag) {
                var begin = Math.max(0, start);
                end = Math.min(9, end);
                if (!item['tags'][tag]) item['tags'][tag] = 0;
                item['tags'][tag] += (end - begin);


                //if(item['item'].length >= 10) return item;
                for (var i = begin; i <= end; i++) {
                    if (item['item'].indexOf(i) >= 0) {
                        item['count'] += 1; //当这分钟已有任务时，累加标记
                        continue;
                    }
                    item['item'].push(i);
                }
                item['time'] = item['item'].length * 10;
                return item;
            };

            //根据时间返回对应数组下标
            this.getIndex = function(time) {
                var h = moment(time).hour();
                var m = moment(time).minute();
                var index = h * 6 + parseInt(m / 10);
                return index;
            }

            for (tskey in data) {
                var tasks = data[tskey];
                for (tkey in tasks) {
                    var tags = tasks[tkey];
                    if (!(tags['started'] && (tags['done'] || tags['toggle'] || tags['cancelled']))) {
                        //标注空心园
                        if(tags['started'] || tags['done'] || tags['cancelled']){
                            this.circleItem(tags);
                        }
                        continue;
                    }
                    this.cutItems(tags);
                }
            }
            //整理成按小时的数组
            var fragmentData1 = [];
            var group = [];
            var i = 0;
            do {
                if (i % 6 == 0) {
                    group = [];
                }
                if (i % 6 == 5) {
                    fragmentData1.push(group);
                }
                group.push(fragmentData[i]);
                i++;
            } while (i < fragmentData.length);

            return fragmentData1;

        };


        //画出碎片图html
        var drawFragment = function(data) {

            var FLAG_SYSTEM = ["critical", "high", "low", "minor", "life"];
            var FLAG_COLOR = ["#1ba4ff", "#72c7ff", "#FF6666", "red", "orange"]; // 浅蓝#72c7ff 天蓝#1ba4ff green yellowgreen orange red

            //获取同一碎片内重叠标签数
            this.isMulti = function(item) {
                return item['count'] > 1;
            }
            //取时间占比最多的标签颜色
            this.getTagColor = function(item) {
                var tag = {};
                for (var i in item['tags']) {
                    if (!tag['key']) tag = { key: i, val: item['tags'][i] };
                    if (item['tags'][i] > tag['val']) tag = { key: i, val: item['tags'][i] };
                }
                if (!tag['key']) return '';

                return FLAG_COLOR[FLAG_SYSTEM.indexOf(tag['key'])];
            }



            var html = $('<div class="fragment"></div>');
            for(var i in data){
                var item = data[i];
                var _item = $('<dl class="fragment-item"></dl>');
                for(k in item ){
                    var multi = this.isMulti(item[k])?' multi':'';
                    var circle = item[k]['circle']?' circle':'';
                    var inner = $('<dt class="fragment-item-inner" title="'+item[k]['title']+'"><div class="fragment-item-inner-progress'+multi+circle+'"><div class="fragment-item-inner-progress-item" style="height:'+item[k]['time']+'%;background-color:'+this.getTagColor(item[k])+';"></div></div></dt>');
                    _item.append(inner);
                }
                html.append(_item);
            }

            return html;

        }



    };

    // CommonJS/Node.js
    if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
        module.exports = factory;
    } else if (typeof define === "function") // AMD/CMD/Sea.js
    {
        if (define.amd) { // for Require.js

            define(["editormd"], function(editormd) {
                factory(editormd);
            });
        } else { // for Sea.js
            define(function(require) {
                var editormd = require("./../../editormd");
                factory(editormd);
            });
        }
    } else {
        factory(window.editormd);
    }

})();